package com.core.common.utils;

/**
 * @author hl
 * @version 1.0.0
 * @ClassName MinioUtil.java
 * @Description 类描述
 * @createTime 2023年05月31日 11:20:00
 */

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.minio.*;
import io.minio.errors.ErrorResponseException;
import io.minio.errors.InsufficientDataException;
import io.minio.errors.InternalException;
import io.minio.errors.InvalidResponseException;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.util.List;
import java.util.Optional;

/**
 * @description:
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class MinioUtil {

    final MinioClient minioClient;

    /**
     * 查看存储bucket是否存在
     * @return boolean
     */
    public static Boolean bucketExists(MinioClient minioClient,String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return found;
    }

    /**
     * @Description 创建桶
     *
     * @param bucketName 桶名称
     */

    public static void makeBucket(MinioClient minioClient,String bucketName) throws Exception {
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }


    /**
     * 删除存储bucket
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * @Description 获取全部bucket
     * <p>
     * https://docs.minio.io/cn/java-client-api-reference.html#listBuckets
     */
    @SneakyThrows
    public  List<Bucket> listBuckets() {
        return minioClient.listBuckets();
    }

    /**
     * @Description 根据bucketName获取信息
     *
     * @param bucketName bucket名称
     */

    public  Optional<Bucket> getBucket(String bucketName) throws Exception {
        return listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
    }





    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public String upload(String bucketName,String objectName,MultipartFile file) {

        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)){
            throw new RuntimeException();
        }
//        String fileName = .generateUuid() + originalFilename.substring(originalFilename.lastIndexOf("."));
//        String objectName = DateUtils.getDayStr() + "/" + fileName;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectName;
    }

    /**
     * 预览
     * @param fileName
     * @return
     */
    public String preview(String fileName,String bucketName){
        // 查看文件地址
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName).object(fileName).method(Method.GET).build();
        try {
            String url = minioClient.getPresignedObjectUrl(build);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     * @param fileName 文件名称
     * @param res response
     * @return Boolean
     */
    public void download(String fileName, String bucketName,HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                // 设置强制下载不打开
                // res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 删除
     * @param fileName
     * @return
     * @throws Exception
     */
    public boolean remove(String fileName,String bucketName){
        try {
            minioClient.removeObject( RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
        }catch (Exception e){
            return false;
        }
        return true;
    }








    /**
     * @Description 获取文件外链
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @return url
     */
    public  String getObjectURL(String bucketName, String objectName) throws Exception {
        return getObjectURL(bucketName, objectName, 7);
    }

    /**
     * @Description 获取文件外链
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @param expires    过期时间 <=7
     * @return url
     */
    public  String getObjectURL(String bucketName, String objectName, Integer expires) throws Exception {
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(objectName).expiry(expires).build());
    }

    /**
     * @Description 获取文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @return 二进制流
     */

    public  InputStream getObject(String bucketName, String objectName) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }

    /**
     * @Description 获取文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @return 二进制流
     */

    public  InputStream getObject(String bucketName, String objectName, long offset, Long length) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).offset(offset).length(length).build());
    }


    /**
     * @Description 获取文件访问地址(有效期)
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @return url
     */
    public  String getPresignedObjectUrl(String bucketName, String objectName) throws Exception {
        return getPresignedObjectUrl(bucketName, objectName, null);
    }

    /**
     * @Description 获取文件访问地址(有效期)
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @param expires    过期时间 <=7
     * @return url
     */
    public  String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws Exception {
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(objectName).build());
    }


    /**
     * @Description 删除文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#removeObject
     */
    public  void removeObject(String bucketName, String objectName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }


    public static String putObject(MinioClient minioClient,String bucketName, String objectName, MultipartFile file) throws Exception {
        if (objectName== null || "".equals(objectName)) {
            objectName = file.getOriginalFilename();
        }
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        makeBucket(minioClient,bucketName);
        minioClient.putObject(args);
     //   return minioConfig.getPreviewUrl() + "/" + bucketName + "/" + objectName;
        return null;
    }


    public static String putObject(MinioClient minioClient,String bucketName, String objectName, File file) throws Exception {

        InputStream inputStream = new FileInputStream(file);
        try {
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(inputStream, file.length(), -1)
                   // .contentType()
                    .build();
            makeBucket(minioClient,bucketName);
            minioClient.putObject(args);
        } catch (Exception e) {
            throw e;
        } finally {
            inputStream.close();
        }
       // return minioConfig.getPreviewUrl() + "/" + bucketName + "/" + objectName;
        return null;
    }

    /**
     * 上传文件
     * @param bucketName
     * @param objectName
     * @param stream
     */
    public void putObject(String bucketName, String objectName, InputStream stream)  {
//        createBucket(bucketName);
//        getMinioClient().putObject(bucketName,objectName,stream,stream.available(),"application/octet-stream");
    }

    public void putObject(String bucketName, String objectName, InputStream stream, int size, String contextType)  {
//        createBucket(bucketName);
//        getMinioClient().putObject(bucketName,objectName,stream,size,contextType);
    }

}
